<template>
  <div class="home-view space-y-4">
    <!-- Quick Navigation -->
    <!-- <QuickNav :layout-config="layoutConfig || []" /> -->

    <!-- Dynamic Layout Sections -->
    <template v-for="section in layoutConfig" :key="section.id">
      <!-- Banner Section -->
      <section 
        v-if="section.type === 'banner' && section.isVisible" 
        :class="section.style?.container" 
        :data-type="section.type"
        ref="bannerSection"
      >
        <!-- Left Category Navigation -->
        <div class="left-nav flex-shrink-0">
          <HomeLeftCategoryNav />
        </div>
        <!-- Right Banner/Carousel -->
        <div class="hero-banner flex-1 overflow-hidden rounded-lg">
          <el-carousel height="460px" arrow="hover">
            <el-carousel-item v-for="item in bannerItems" :key="item.id">
              <router-link v-if="item.path && item.path.startsWith('/')" :to="item.path">
                <img :src="item.pic" :alt="item.description" class="w-full h-full object-cover" @error="handleImageError" />
              </router-link>
              <a v-else :href="item.path || '#'" target="_blank" rel="noopener noreferrer">
                <img :src="item.pic" :alt="item.description" class="w-full h-full object-cover" @error="handleImageError" />
              </a>
            </el-carousel-item>
          </el-carousel>
        </div>
      </section>

      <!-- Flash Sale Section -->
      <section 
        v-else-if="section.type === 'flash-sale' && section.isVisible" 
        :class="section.style?.container" 
        :data-type="section.type"
        class="animate-section"
      >
        <FlashSaleSection />
      </section>

      <!-- Product Showcase Section -->
      <section 
        v-else-if="section.type === 'product-showcase' && section.isVisible" 
        :class="section.style?.container" 
        :data-type="section.type"
        class="animate-section"
      >
        <h2 v-if="section.showTitle" :class="section.style?.title">{{ section.title }}</h2>
        <ProductShowcase 
          :title="section.title"
          :featured-product="getFeaturedProduct(section.categoryId!)"
          :products="getProductsByCategory(section.categoryId!)"
        />
      </section>

      <!-- Product Grid Section -->
      <section 
        v-else-if="section.type === 'product-grid' && section.isVisible" 
        :class="section.style?.container" 
        :data-type="section.type"
        class="animate-section"
      >
        <h2 v-if="section.showTitle" :class="section.style?.title">{{ section.title }}</h2>
        <ProductGrid 
          :title="section.title"
          :products="getProductsByCategory(section.categoryId!)"
        />
      </section>

      <!-- Product Carousel Section -->
      <section 
        v-else-if="section.type === 'product-carousel' && section.isVisible" 
        :class="section.style?.container" 
        :data-type="section.type"
        class="animate-section"
      >
        <h2 v-if="section.showTitle" :class="section.style?.title">{{ section.title }}</h2>
        <ProductCarousel 
          :title="section.title"
          :products="getProductsByCategory(section.categoryId!)"
        />
      </section>

      <!-- Brands Section -->
      <section 
        v-else-if="section.type === 'brands' && section.isVisible" 
        :class="section.style?.container" 
        :data-type="section.type"
        class="animate-section"
      >
        <div class="flex justify-between items-center mb-6">
          <h2 v-if="section.showTitle" :class="section.style?.title">{{ section.title }}</h2>
          <router-link :to="`/products?category=${section.categoryId}`" class="text-sm text-gray-500 hover:text-purple-600 transition-colors">查看全部 &gt;</router-link>
        </div>
        <div class="grid grid-cols-5 gap-4 brand-grid">
          <router-link :to="`/products?brand=${brand.brandID}`" v-for="(brand, index) in featuredBrands" :key="index"
             class="brand-item block p-4 text-center border border-gray-100 rounded-lg transition-all duration-300 hover:shadow-md hover:border-purple-200 hover:scale-[1.02]">
             <img :src="brand.logoUrl" :alt="brand.name" class="max-h-12 mb-3 object-contain mx-auto" @error="handleImageError">
             <h3 class="font-medium text-sm text-gray-600 truncate">{{ brand.name }}</h3>
          </router-link>
        </div>
      </section>

      <!-- New Arrivals Section -->
      <section 
        v-else-if="section.type === 'new-arrivals' && section.isVisible" 
        :class="section.style?.container" 
        :data-type="section.type"
        class="animate-section"
      >
        <h2 v-if="section.showTitle" :class="section.style?.title">{{ section.title }}</h2>
        <div class="grid grid-cols-4 gap-5 products-grid">
          <router-link
            v-for="product in getProductsByCategory(section.categoryId!)"
            :key="product.id"
            :to="`/product/${product.id}`"
            class="product-item group block bg-white border border-gray-200 rounded-lg overflow-hidden hover:shadow-xl transform transition-all duration-300 hover:-translate-y-1"
          >
            <div class="block overflow-hidden h-60">
              <img :src="product.imgUrl" :alt="product.name" class="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300" @error="handleImageError" />
            </div>
            <div class="p-4 text-sm text-center">
              <p class="text-gray-700 truncate mb-1 group-hover:text-blue-600 font-medium">{{ product.name }}</p>
              <p v-if="product.specification" class="text-gray-500 text-xs truncate mb-1">规格: {{ product.specification }}</p>
              <p class="text-red-500 text-lg font-semibold">{{ formatPriceAuth(product.price, !!userStore.token) }}</p>
              <div class="text-xs text-gray-400 mt-1 flex justify-center space-x-2">
                <span v-if="product.salesVolume !== undefined">已售: {{ product.salesVolume }}</span>
                <span v-if="product.stockLevel !== undefined">库存: {{ product.stockLevel }}</span>
              </div>
            </div>
          </router-link>
        </div>
      </section>

      <!-- Topics Section -->
      <section 
        v-else-if="section.type === 'topics' && section.isVisible" 
        :class="section.style?.container" 
        :data-type="section.type"
        class="animate-section"
      >
        <div class="flex justify-between items-center mb-4">
          <h2 v-if="section.showTitle" :class="section.style?.title">{{ section.title }}</h2>
          <router-link :to="`/products?attribute=${section.categoryId}`" class="text-sm text-gray-500 hover:text-blue-600 transition-colors">查看全部 &gt;</router-link>
        </div>
        <div class="grid grid-cols-3 gap-5 topics-grid">
          <div v-for="topic in relatedTopicsData" :key="topic.id" class="topic-card border border-gray-200 rounded-lg overflow-hidden hover:shadow-xl transition-all duration-300 bg-white transform hover:scale-[1.02]">
            <img :src="topic.image" :alt="topic.title" class="w-full h-40 object-cover" @error="handleImageError" />
            <div class="p-4">
              <h3 class="font-medium mb-1 truncate text-gray-800">{{ topic.title }}</h3>
              <p class="text-sm text-gray-500 mb-2 truncate h-10">{{ topic.description }}</p>
              <div class="flex justify-between items-center text-xs text-gray-400">
                <span class="flex items-center"><el-icon class="mr-1"><Star /></el-icon>{{ topic.likes }}</span>
                <span class="flex items-center"><el-icon class="mr-1"><View /></el-icon>{{ topic.views }}</span>
                <span class="flex items-center"><el-icon class="mr-1"><ChatLineSquare /></el-icon>{{ topic.comments }}</span>
              </div>
            </div>
          </div>
        </div>
      </section>

      <!-- Reviews Section -->
      <section 
        v-else-if="section.type === 'reviews' && section.isVisible" 
        :class="section.style?.container" 
        :data-type="section.type"
        class="animate-section"
      >
        <h2 v-if="section.showTitle" :class="section.style?.title">{{ section.title }}</h2>
        <div class="grid grid-cols-3 gap-5 reviews-grid">
          <div v-for="(review, index) in userReviews" :key="index" class="review-card bg-white p-4 rounded-lg border-l-4 border-teal-400 shadow-sm hover:shadow-lg transition-shadow flex gap-4 items-start">
            <img :src="review.avatar" :alt="review.user" class="w-12 h-12 rounded-full flex-shrink-0" @error="handleImageError">
            <div class="text-sm flex-1">
              <p class="text-gray-600 mb-2 h-16 overflow-hidden leading-relaxed">{{ review.comment }}</p>
              <p class="text-gray-400 text-xs">{{ review.user }} {{ review.date }}</p>
              <p class="text-gray-700 font-medium mt-1 truncate">{{ review.productName }}</p>
            </div>
          </div>
        </div>
      </section>

      <!-- User Activity Section -->
      <section 
        v-else-if="section.type === 'user-activity' && section.isVisible" 
        :class="section.style?.container" 
        :data-type="section.type"
        class="animate-section"
      >
        <!-- My Footprints -->
        <div class="footprints-module bg-white p-5 rounded-lg shadow-sm border border-gray-100">
          <div class="flex justify-between items-center mb-4">
            <h3 class="text-xl font-semibold text-gray-800 flex items-center">
              <span class="mr-2">👣</span> 我的足迹
            </h3>
            <router-link :to="`/profile/footprints`" class="text-sm text-gray-500 hover:text-purple-600 transition-colors">查看更多 &gt;</router-link>
          </div>
          <div class="space-y-4">
            <div
              v-for="product in footprintItems"
              :key="product.id"
              class="favorite-item group bg-gray-50 rounded-lg p-4 flex items-start gap-6 hover:bg-gray-100 transition-all duration-300"
            >
              <!-- Product Image -->
              <router-link :to="`/product/${product.id}`" class="block w-32 h-32 flex-shrink-0">
                <img :src="product.mainPic || ''" :alt="product.title" class="w-full h-full object-cover rounded-lg shadow-sm" @error="handleImageError" />
              </router-link>

              <!-- Product Info -->
              <div class="flex-1 min-w-0">
                <!-- Title and Basic Info -->
                <div class="flex justify-between items-start mb-2">
                  <div class="flex-1">
                    <router-link :to="`/product/${product.id}`" class="block group-hover:text-blue-600">
                      <h4 class="font-medium text-gray-900 text-lg mb-1">{{ product.title }}</h4>
                    </router-link>
                  </div>
                </div>

                <div>
                  <div class="flex items-center gap-2 flex-wrap">
                    <span class="text-xs px-2 py-1 bg-blue-50 text-blue-600 rounded">{{ product.gCategory }}</span>
                    <span class="text-xs px-2 py-1 bg-purple-50 text-purple-600 rounded">{{ product.qCategory }}</span>
       
                    <span v-if="product.formula" class="text-xs px-2 py-1 bg-green-50 text-green-600 rounded">{{ product.formula }}</span>
                  </div>
                </div>

                <!-- Detailed Info Grid -->
                <div class="grid grid-cols-3 gap-4 mt-3">
                  <!-- Column 1 -->
                  <div class="space-y-2">
                    <div>
                      <p class="text-xs text-gray-500">生产厂家</p>
                      <p class="text-sm text-gray-700 truncate">{{ product.manufacturer }}</p>
                    </div>
                    <div>
                      <p class="text-xs text-gray-500">商品规格</p>
                      <p class="text-sm text-gray-700">{{ product.goodsSpec }}</p>
                    </div>
                  </div>

                  <!-- Column 2 -->
                  <div class="space-y-2">
                    <div>
                      <p class="text-xs text-gray-500">批准文号</p>
                      <p class="text-sm text-gray-700 truncate">{{ product.approvalNo }}</p>
                    </div>
                    <div>
                      <p class="text-xs text-gray-500">包装单位</p>
                      <p class="text-sm text-gray-700">{{ product.unit }}</p>
                    </div>
                  </div>

                  <!-- Column 3 -->
                  <div class="space-y-2">
                    <div class="flex items-baseline justify-between">
                      <span class="text-red-500 text-lg font-semibold">{{ formatPriceAuth(product.price, !!userStore.token, userStore.userInfo?.discount, product.noDiscounts) }}</span>
                    </div>
                    <div>
                      <span class="text-xs text-gray-500">库存: <span :class="getStockStatusClass(product.storNum)">{{ getStockStatusText(product.storNum) }}</span></span>
                    </div>
                  </div>
                </div>

                <!-- Additional Info -->
                <div class="mt-3 flex items-center justify-between text-xs text-gray-500 border-t pt-2">
                  <div class="flex items-center gap-4">
                    <span>访问次数: {{ product.visitCount || 0 }}</span>
                    <span>最近访问: {{ product.lastVisitTime }}</span>
                  </div>
                </div>
              </div>
            </div>
            <p v-if="!footprintItems.length" class="text-center text-gray-400 py-8">暂无浏览记录</p>
          </div>
        </div>

        <!-- My Favorites -->
        <div class="favorites-module bg-white p-5 rounded-lg shadow-sm border border-gray-100 mt-6">
          <div class="flex justify-between items-center mb-4">
            <h3 class="text-xl font-semibold text-gray-800 flex items-center">
              <span class="mr-2">💖</span> 我的收藏
            </h3>
            <router-link :to="`/profile/favorites`" class="text-sm text-gray-500 hover:text-purple-600 transition-colors">查看更多 &gt;</router-link>
          </div>
          <div class="space-y-4">
            <div
              v-for="product in userFavorites"
              :key="product.id"
              class="favorite-item group bg-gray-50 rounded-lg p-4 flex items-start gap-6 hover:bg-gray-100 transition-all duration-300"
            >
              <!-- Product Image -->
              <router-link :to="`/product/${product.id}`" class="block w-32 h-32 flex-shrink-0">
                <img :src="product.imgUrl" :alt="product.name" class="w-full h-full object-cover rounded-lg shadow-sm" @error="handleImageError" />
              </router-link>

              <!-- Product Info -->
              <div class="flex-1 min-w-0">
                <!-- Title and Basic Info -->
                <div class="flex justify-between items-start mb-2">
                  <div class="flex-1">
                    <router-link :to="`/product/${product.id}`" class="block group-hover:text-blue-600">
                      <h4 class="font-medium text-gray-900 text-lg mb-1">{{ product.name }}</h4>
                    </router-link>
                  </div>
                  <el-button type="danger" plain size="small" class="ml-4 flex-shrink-0" @click="collectStore.toggleCollect(product.id)">
                    <el-icon><Delete /></el-icon>
                    取消收藏
                  </el-button>
                </div>
                <div>
                <div class="flex items-center gap-2 flex-wrap">
                      <span class="text-xs px-2 py-1 bg-blue-50 text-blue-600 rounded">{{ product.gCategory }}</span>
                      <span class="text-xs px-2 py-1 bg-purple-50 text-purple-600 rounded">{{ product.qCategory }}</span>

                      <span v-if="product.formula" class="text-xs px-2 py-1 bg-green-50 text-green-600 rounded">{{ product.formula }}</span>
                    </div>
                </div>
                <!-- Detailed Info Grid -->
                <div class="grid grid-cols-3 gap-4 mt-3">
                  <!-- Column 1 -->
                  <div class="space-y-2">
                    <div>
                      <p class="text-xs text-gray-500">生产厂家</p>
                      <p class="text-sm text-gray-700 truncate">{{ product.manufacturer }}</p>
                    </div>
                    <div>
                      <p class="text-xs text-gray-500">商品规格</p>
                      <p class="text-sm text-gray-700">{{ product.goodsSpec }}</p>
                    </div>
                  </div>

                  <!-- Column 2 -->
                  <div class="space-y-2">
                    <div>
                      <p class="text-xs text-gray-500">批准文号</p>
                      <p class="text-sm text-gray-700 truncate">{{ product.approvalNo }}</p>
                    </div>
                    <div>
                      <p class="text-xs text-gray-500">包装单位</p>
                      <p class="text-sm text-gray-700">{{ product.unit }}</p>
                    </div>
                  </div>

                  <!-- Column 3 -->
                  <div class="space-y-2">
                    <div class="flex items-baseline justify-between">
                      <span class="text-red-500 text-lg font-semibold">{{ formatPriceAuth(product.price, !!userStore.token, userStore.userInfo?.discount, product.noDiscounts) }}</span>
                    </div>
                    <div>
                      <span class="text-xs text-gray-500">库存: <span :class="getStockStatusClass(product.storNum)">{{ getStockStatusText(product.storNum) }}</span></span>
                    </div>
                  </div>
                </div>
        

                <!-- Additional Info -->
                <div class="mt-3 flex items-center justify-between text-xs text-gray-500 border-t pt-2">
                  <div class="flex items-center gap-4">
                    <span>商品编码: {{ product.goodsCode }}</span>
                    <span>销量: {{ product.sold }}+</span>
                  </div>
                </div>
              </div>
            </div>
            <p v-if="!userFavorites.length" class="text-center text-gray-400 py-8">暂无收藏商品</p>
          </div>
        </div>
      </section>
    </template>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue'
import HomeLeftCategoryNav from './home/components/HomeLeftCategoryNav.vue'
import FlashSaleSection from './home/components/FlashSaleSection.vue'
import ProductShowcase from './home/components/ProductShowcase.vue'
import ProductGrid from './home/components/ProductGrid.vue'
import ProductCarousel from './home/components/ProductCarousel.vue'
import { getLayoutConfig, getBannerList, getBrandList } from '@/api/modules/layout'
import { getGoodsList } from '@/api/modules/goods'
import type { LayoutConfig, BannerItem, BrandItem } from '@/api/modules/layout'
import type { Goods } from '@/api/modules/goods'
import { useCollectStore } from '@/stores/collect'
import { useFootprintStore } from '@/stores/footprint'
import { useUserStore } from '@/stores/user'
import { Star, View, ChatLineSquare, Delete } from '@element-plus/icons-vue'
import { animations, animationUtils } from '@/components/animations/GSAPAnimations'
import { formatPriceAuth } from '@/lib/utils'
import { getStockStatusText, getStockStatusClass } from '@/lib/stockUtils'

// Extended interface for frontend display
export interface DisplayGoods {
  // Base properties
  id: number
  createTime: string
  updateTime: string
  tenantId: number | null
  typeId: number
  title: string
  subTitle: string | null
  mainPic: string | null
  pics: string | null
  price: string
  sold: number
  content: string | null
  status: number
  sortNum: number
  goodsId: string
  entId: string
  goodsCode: string
  oracleGoodsName: string
  goodsSpec: string
  manufacturer: string
  unit: string
  approvalNo: string
  formula: string
  midpack: number
  qty: string
  planCate: string | null
  logogram: string
  wholLimtNum: number
  storNum: string
  isMidpackSaleDisabled: number
  gCategory: string
  qCategory: string
  oracleIsHidden: number
  isPres: number
  attribute: string
  // Display-specific properties
  name: string
  imgUrl: string
  specification: string
  salesVolume: number
  stockLevel: number
  expiryDate?: string
  category?: number
  typeName: string
  visitCount?: number
  lastVisitTime?: string
  originalPrice?: string
  nearestExpiredDate?: string
  noDiscounts: number
}

// --- Data Setup ---

// Banner Data - Changed to ref<BannerItem[]>
const bannerItems = ref<BannerItem[]>([])

// Re-add Category interface
interface Category {
  label: string
  value: number
}

// Product Categories
const productCategories = ref<Category[]>([
  { label: '新品上市', value: 1 },
  { label: '热销药品', value: 2 },
  { label: '推荐药品', value: 3 },
  { label: '特价药品', value: 4 },
  { label: '畅销药品', value: 5 },
  { label: '精品药品', value: 6 },
  { label: '优选药品', value: 7 },
  { label: '限购药品', value: 8 }
])

// Category Products Map
const categoryProductsMap = ref<Map<number, DisplayGoods[]>>(new Map())

// Helper function to transform backend goods to display format
const transformGoodsToDisplay = (goods: Goods): DisplayGoods => {
  return {
    ...goods,
    name: goods.title,
    imgUrl: goods.mainPic || '',
    specification: goods.goodsSpec || '',
    salesVolume: goods.sold || 0,
    stockLevel: Number(goods.storNum) || 0,
    category: goods.typeId,
    typeName: goods.typeName || '',
    visitCount: goods.visitCount || 0,
    lastVisitTime: formatDate(goods.lastVisitTime),
    // Map additional properties
    title: goods.title,
    mainPic: goods.mainPic,
    approvalNo: goods.approvalNo,
    goodsSpec: goods.goodsSpec,
    formula: goods.formula,
    sold: goods.sold,
    isPres: goods.isPres,
    wholLimtNum: goods.wholLimtNum,
    storNum: goods.storNum,
    noDiscounts: Number(goods.noDiscounts || 0)
  }
}

// Format date helper
function formatDate(date: string | undefined): string {
  if (!date) return '-'
  const now = new Date()
  const visitDate = new Date(date)
  const diff = now.getTime() - visitDate.getTime()
  
  // 小于1分钟
  if (diff < 60000) return '刚刚'
  // 小于1小时
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
  // 小于24小时
  if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`
  // 小于7天
  if (diff < 604800000) return `${Math.floor(diff / 86400000)}天前`
  
  // 其他情况显示具体日期
  return visitDate.toLocaleDateString('zh-CN', { 
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// Fetch products by category
const fetchProductsByCategory = async (categoryId: number) => {
  try {
    const response: any = await getGoodsList({
      page: 1,
      size: 10,
      attribute: [categoryId]
    })
    
    if (response.data?.list) {
      const displayGoods = response.data.list.map(transformGoodsToDisplay)
      categoryProductsMap.value.set(categoryId, displayGoods)
    }
  } catch (error) {
    console.error(`Failed to fetch products for category ${categoryId}:`, error)
  }
}

// Fetch all category products
const fetchAllCategoryProducts = async () => {
  // Add type Category to parameter
  const promises = productCategories.value.map((category: Category) => 
    fetchProductsByCategory(category.value)
  )
  await Promise.all(promises)
}

// Get products by category
const getProductsByCategory = (categoryId: number): DisplayGoods[] => {
  return categoryProductsMap.value.get(categoryId) || []
}

// Define DisplayBrand interface for frontend use
interface DisplayBrand {
  name: string;
  logoUrl: string; // Keep logoUrl for the template
  id: number; // Add id if needed
  brandID: number; // Add brandID for filtering
}

// Featured Brands Data - Changed to ref<DisplayBrand[]>
const featuredBrands = ref<DisplayBrand[]>([])

// Fetch Featured Brands
const fetchFeaturedBrands = async () => {
  try {
    const response:any = await getBrandList() // Assuming getBrandList returns { code, data, message } structure
    if (response.code === 1000 && response.data) {
      // Map BrandItem (backend) to DisplayBrand (frontend)
      featuredBrands.value = response.data.map((item: BrandItem) => ({
        id: item.id,
        brandID: item.brandID,
        name: item.name,
        logoUrl: item.url // Map url to logoUrl
      }))
    } else {
      console.error('Failed to fetch featured brands:', response.message)
      // Optionally set fallback brands
      featuredBrands.value = [
        { id: 999, brandID: 999, name: 'Fallback Brand', logoUrl: 'https://picsum.photos/seed/fallbackbrand/120/50' }
      ]
    }
  } catch (error) {
    console.error('Error fetching featured brands:', error)
     // Optionally set fallback brands
     featuredBrands.value = [
       { id: 999, brandID: 999, name: 'Fallback Brand', logoUrl: 'https://picsum.photos/seed/fallbackbrand/120/50' }
     ]
  }
}

// Topics Data
interface Topic { id: number; title: string; description: string; image: string; likes: string; views: string; comments: string; }
const relatedTopicsData = ref<Topic[]>([
  { id: 1, title: '春季过敏防护指南', description: '远离过敏困扰，畅享春天', image: 'https://picsum.photos/seed/allergy/300/150', likes: '1.2k', views: '11k', comments: '88' },
  { id: 2, title: '如何科学补充维生素', description: '不同人群的维生素需求', image: 'https://picsum.photos/seed/vitamins/300/150', likes: '2.5k', views: '20k', comments: '180' },
  { id: 3, title: '家庭药箱必备清单', description: '有备无患，守护家人健康', image: 'https://picsum.photos/seed/medkit/300/150', likes: '3k', views: '25k', comments: '210' },
]);

// Reviews Data
interface Review {
  user: string;
  date: string;
  comment: string;
  productName: string;
  avatar: string;
}
const userReviews = ref<Review[]>([
  { user: '张三', date: '2024-05-01', comment: '这款感冒药效果很好，吃了两天就好多了，物流也很快！', productName: '感冒灵颗粒', avatar: 'https://picsum.photos/seed/zhang/80/80' },
  { user: '李四', date: '2024-04-28', comment: '血压计测量准确，操作简单，家里老人用很方便。', productName: '欧姆龙血压计', avatar: 'https://picsum.photos/seed/li/80/80' },
  { user: '王五', date: '2024-04-25', comment: '维生素C味道不错，每天一片，感觉抵抗力增强了。', productName: '维生素C泡腾片', avatar: 'https://picsum.photos/seed/wang/80/80' },
]);

// User Footprints Data
const footprintStore = useFootprintStore()
const footprintItems:any = computed(() => footprintStore.footprintItems.map((item:any) => transformGoodsToDisplay(item)))

// User Favorites Data  
const collectStore = useCollectStore()

// 转换收藏商品为 DisplayGoods 格式
const userFavorites:any = computed(() => {
  return collectStore.collectItems.map((item:any) => ({
    ...item,
    name: item.title,
    imgUrl: item.mainPic || '',
    specification: item.goodsSpec,
    salesVolume: item.sold,
    stockLevel: Number(item.storNum),
    category: item.typeId,
    typeName: '',
    noDiscounts: Number(item.noDiscounts || 0)
  }))
})

// Get featured product for category
const getFeaturedProduct = (categoryId: number): DisplayGoods | null => {
  const products = getProductsByCategory(categoryId)
  return products.length > 0 ? products[0] : null
}

// Layout Configuration
const layoutConfig = ref<LayoutConfig[]>()

// Fetch layout configuration from backend
const fetchLayoutConfig = async () => {
  try {
    const response:any = await getLayoutConfig()
    if (response.code === 1000 && response.data) {
      // Merge backend config with default config
      const backendConfig = response.data
      console.log(backendConfig)
      layoutConfig.value = backendConfig.sort((a:any, b:any) => a.order - b.order)
    }
  } catch (error) {
    console.error('Failed to fetch layout configuration:', error)
  }
}

// Animation instances
let sectionAnimations: gsap.core.Tween[] = []

// Setup scroll-triggered animations
function setupScrollAnimations() {
  // Use nextTick to ensure DOM is ready
  nextTick(() => {
    // Animate all sections with the animate-section class
    const animateSections = document.querySelectorAll('.animate-section')
    
    animateSections.forEach((section) => {
      const animation = animations.scrollTriggerFadeIn(section as Element, {
        start: "top 80%",
        end: "bottom 20%"
      })
      sectionAnimations.push(animation)
      
      // Add stagger animation for grid items within sections
      const gridItems = section.querySelectorAll('.brand-grid .brand-item, .products-grid .product-item, .topics-grid .topic-card, .reviews-grid .review-card')
      if (gridItems.length > 0) {
        const staggerAnimation = animations.staggerFadeIn(Array.from(gridItems), {
          delay: 0.2,
          stagger: 0.1
        })
        sectionAnimations.push(staggerAnimation)
      }
    })
  })
}

// Fetch layout config and products on component mount
onMounted(async () => {
  await Promise.all([
    fetchLayoutConfig(),
    fetchAllCategoryProducts(),
    fetchBannerItems(),
    fetchFeaturedBrands(),
    footprintStore.fetchFootprintList(1, 5),
    collectStore.fetchCollectList(1, 5)
  ])
  
  // Setup animations after content is loaded
  setupScrollAnimations()
})

// Cleanup animations on unmount
onUnmounted(() => {
  sectionAnimations.forEach(animation => {
    animationUtils.cleanup(animation)
  })
  sectionAnimations = []
})

// 添加后备图片常量
const fallbackImage = '/images/no.jpg'

// 图片错误处理函数
function handleImageError(e: Event) {
  const target = e.target as HTMLImageElement
  if (target) {
    target.src = fallbackImage
  }
}

// --- Fetch Banner Data ---
const fetchBannerItems = async () => {
  try {
    const response:any = await getBannerList()
    // Access data via response.data
    if (response.code === 1000 && response.data) {
      bannerItems.value = response.data
    } else {
      console.error('Failed to fetch banner items:', response.data.message)
      // Optionally set fallback banners or show an error message
      bannerItems.value = [ // Example fallback
        { id: 999, pic: 'https://picsum.photos/seed/fallback/1000/460', description: 'Fallback Banner', path: '#', type: 2 }
      ]
    }
  } catch (error) {
    console.error('Error fetching banner items:', error)
    // Optionally set fallback banners
    bannerItems.value = [ // Example fallback
       { id: 999, pic: 'https://picsum.photos/seed/fallback/1000/460', description: 'Fallback Banner', path: '#', type: 2 }
    ]
  }
}

const userStore = useUserStore()

</script>

<style scoped>
.product-item .text-gray-400 {
    height: 1rem; /* Ensure consistent height for description */
    min-height: 1rem; /* Add min-height for safety */
}

/* GSAP Animation Classes */
.animate-section {
  opacity: 0;
  transform: translateY(30px);
  transition: all 0.3s ease;
}

.animate-section.gsap-animated {
  opacity: 1;
  transform: translateY(0);
}

/* Enhanced hover effects for animated elements */
.brand-item {
  transition: all 0.3s ease;
}

.brand-item:hover {
  transform: translateY(-5px) scale(1.05);
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
}

.product-item {
  transition: all 0.3s ease;
}

.product-item:hover {
  transform: translateY(-8px);
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.15);
}

.topic-card {
  transition: all 0.3s ease;
}

.topic-card:hover {
  transform: translateY(-5px) scale(1.02);
  box-shadow: 0 12px 30px rgba(0, 0, 0, 0.12);
}

.review-card {
  transition: all 0.3s ease;
}

.review-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
}

/* Floating animation for special elements */
@keyframes float {
  0%, 100% {
    transform: translateY(0px);
  }
  50% {
    transform: translateY(-10px);
  }
}

.floating-element {
  animation: float 3s ease-in-out infinite;
}

/* Medical theme enhancements */
.footprints-module, .favorites-module {
  position: relative;
  overflow: hidden;
}

.footprints-module::before,
.favorites-module::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(59, 130, 246, 0.05), transparent);
  transition: left 0.8s;
}

.footprints-module:hover::before,
.favorites-module:hover::before {
  left: 100%;
}

/* Section titles enhancement */
section h2 {
  position: relative;
  display: inline-block;
}

section h2::after {
  content: '';
  position: absolute;
  bottom: -4px;
  left: 0;
  width: 0;
  height: 2px;
  background: linear-gradient(90deg, #dc2626, #f59e0b);
  transition: width 0.5s ease;
}

section:hover h2::after {
  width: 100%;
}

/* Ensure ElIcon size is consistent */
.el-icon {
  font-size: 1.1em; /* Adjust if needed */
  vertical-align: middle;
}

/* Responsive adjustments for animations */
@media (max-width: 768px) {
  .animate-section {
    transform: translateY(20px);
  }
  
  .brand-item:hover,
  .product-item:hover,
  .topic-card:hover,
  .review-card:hover {
    transform: none;
    box-shadow: none;
  }
}
</style> 